package com.example.core.init;

import com.example.core.lock.RedisLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class SysInitServiceImpl implements InitializingBean, CommandLineRunner, DisposableBean {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private List<SysInitService> initServices = new ArrayList<>();

    @Resource
    private RedissonClient redissonClient;

    @Override
    public void destroy() throws Exception {
        RedisLock lock = null;
        try {
            lock = new RedisLock(redissonClient, getClass().getName());
            lock.lock();
            for (SysInitService initService : initServices) {
                initService.start();
            }
        } catch (Exception e) {
            logger.error("SysInitServiceImpl destroy error : " + e.getMessage());
        } finally {
            if (lock != null) {
                lock.unlock();
            }
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        RedisLock lock = null;
        try {
            lock = new RedisLock(redissonClient, getClass().getName());
            lock.lock();
            for (SysInitService initService : initServices) {
                initService.init();
            }
        } catch (Exception e) {
            logger.error("SysInitServiceImpl afterPropertiesSet error : " + e.getMessage());
        } finally {
            if (lock != null) {
                lock.unlock();
            }
        }
    }

    @Override
    public void run(String... args) throws Exception {
        RedisLock lock = null;
        try {
            lock = new RedisLock(redissonClient, getClass().getName());
            lock.lock();
            for (SysInitService initService : initServices) {
                initService.start();
            }
        } catch (Exception e) {
            logger.error("SysInitServiceImpl run error : " + e.getMessage());
        } finally {
            if (lock != null) {
                lock.unlock();
            }
        }
    }
}
